<template>
    <div class="app-container" v-loading="fullscreenLoading">
        <div class="filter-container">
            <el-form :inline="true" class="demo-form-inline" label-position="left">
                <!-- <el-form-item label="月份" label-width="50px">
                    <el-date-picker v-model="search.month" type="month" placeholder="选择月" style="width: 140px;">
                    </el-date-picker>
                </el-form-item> -->
                <el-form-item label="执行人归属" label-width="90px">
                    <el-select v-model="search.subBelonging" filterable placeholder="执行人归属" remote style="width: 140px;"
                        :remote-method="remoteMethodOrg" :loading="loading">
                        <el-option v-for="item in orgList" :key="item.cityName" :label="item.cityName"
                            :value="item.cityName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="执行人" label-width="60px">
                    <el-select v-model="search.batchExecutor" filterable remote placeholder="请输入执行人" clearable
                        style="width: 140px;" :remote-method="remoteMethod" :loading="loading">
                        <el-option v-for="item in options" :key="item.userName"
                            :label="`${item.acName}(${item.cityName})`" :value="item.userName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="目标状态" label-width="70px">
                    <el-select v-model="search.taskState" placeholder="请选择" style="width: 140px;" clearable>
                        <el-option v-for="item, i in typeOptions" :key="i" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="类型" label-width="50px">
                    <el-select v-model="search.taskType" placeholder="请选择" style="width: 140px;"
                        @change="changeTaskType">
                        <el-option v-for="item, i in okrType" :key="i" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="科室" label-width="45px" v-if="search.taskType === '20'">
                    <tree-select :data="treeSelectData" :defaultProps="treeDefaultProps" :nodeKey="treeNodeKey"
                        width="180" :checkedKeys="treeDefaultCheckedKeys" :isAddState='isAddState'
                        @popoverHide="popoverHide"></tree-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                    <el-button type="primary" @click="down">导出</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table-box-y">
            <div class="table-content" v-for="item, i in dataList" :key="i">
                <div class="table-title">
                    <span class="hover-go" @click="goDetail(item)"><b>目标{{ i + 1 }}：</b>{{ item.mainName || '--'
                        }}</span>
                </div>
                <div class="table-title">
                    <div class="table-label" v-if="searchContent.taskType === '10'">承接专项：{{ item.specializedName || '--'
                        }}</div>
                    <div class="table-label" v-if="searchContent.taskType === '20'">科室：{{ item.deptName || '--' }}</div>
                    <div class="table-label">执行人：{{ item.executorAcName || '--' }}</div>
                    <div class="table-label">计划完成时间：{{ item.planEndTime || '--' }}</div>
                    <div class="table-label">时间进度：{{ item.timeProgress ? truncateToFixed(item.timeProgress, 1) : 0 }}%
                    </div>
                    <!-- <div class="table-label">落实情况：<span
                            :style="{ color: getColor(item.taskImplementation), fontWeight: 900 }">{{
                                item.taskImplementation }}</span></div> -->
                    <div class="table-label">当前状态：<span :style="{ color: getColor(item.taskState), fontWeight: 900 }">{{
                        getStateName(item.taskState) }}</span>
                    </div>
                </div>
                <el-table :data="item.secondList || []" style="width: 100%;" border class="table-box"
                    :span-method="(e) => objectSpanMethod(e, item.secondList || [], i)">
                    <el-table-column label="序号" width="70">
                        <template slot-scope="scope">
                            {{ indexNum[i][scope.$index] + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        :label="searchContent.taskType === '10' ? '部门关键结果' : searchContent.taskType === '20' ? '科室关键结果' : searchContent.taskType === '30' || searchContent.taskType === '60' ? '调度关键结果' : '调度关键结果'">
                        <template slot-scope="scope">
                            <b>关键结果{{ indexNum[i][scope.$index] + 1 }}：</b>{{ scope.row.subName }}
                        </template>
                    </el-table-column>
                    <el-table-column label="负责团队" width="120">
                        <template slot-scope="scope">
                            {{ scope.row.subExecutorAcNames || 0 }}
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="自评分" width="80">
                        <template slot-scope="scope">
                            {{ scope.row.finishProgress || 0 }}
                        </template>
                    </el-table-column> -->
                    <el-table-column
                        :label="searchContent.taskType != '30' && searchContent.taskType != '60' ? `本月关键结果` : '指标名称'">
                        <template slot-scope="scope">
                            <b>{{ searchContent.taskType != '30' && searchContent.taskType != '60' ?
                                `关键结果${scope.row.idx
                                + 1}：` : `指标名称${scope.row.idx +
                                1}：` }}</b>
                            <br />
                            <span v-html="getTextToBr(scope.row.taskName)"></span>
                        </template>
                    </el-table-column>
                    <el-table-column label="达成情况"
                        v-if="searchContent.taskType != '30' && searchContent.taskType != '60'">
                        <template slot-scope="scope">
                            <!-- <b>达成情况{{ scope.row.idx + 1 }}：</b>
                            <br /> -->
                            <span v-html="getTextToBr(scope.row.taskDescription)"></span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="完成进度" width="100" v-if="searchContent.taskType !='30'">
                    <template slot-scope="scope">
                        {{ scope.row.progress || 0 }}%
                    </template>
                </el-table-column> -->
                    <el-table-column label="计划完成时间" width="150"
                        v-if="searchContent.taskType != '30' && searchContent.taskType != '60'">
                        <template slot-scope="scope">
                            {{ scope.row.endTime || '--' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="自评分" width="100"
                        v-if="searchContent.taskType != '30' && searchContent.taskType != '60'">
                        <template slot-scope="scope">
                            {{ scope.row.selfRating }}
                        </template>
                    </el-table-column>
                    <el-table-column label="指标值" width="150"
                        v-if="searchContent.taskType == '30' || searchContent.taskType == '60'">
                        <template slot-scope="scope">
                            {{ scope.row.indexValue }}
                        </template>
                    </el-table-column>
                    <el-table-column label="执行人" width="100">
                        <template slot-scope="scope">
                            {{ scope.row.batchExecutorAcName }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-if="!dataList.length" class="empty-box">
                <img src="../../assets/img/empty.png" width="180" />
                <div>{{ getIsSearch() ? '请输入搜索条件后查询' : '暂无数据' }}</div>
            </div>
        </div>
    </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { getPersonList, getOrg, getOkrList } from '@/api/api'
import qs from 'querystring'
import treeSelect from '@/components/treeSelect'
let orgs = [...orgList]
let orgIndex = orgs.findIndex(item => item.label === '所有科室')
if (orgIndex > -1) {
    orgs.splice(orgIndex, 1)
}
let org = orgs
export default {
    name: 'workList',
    components: { Pagination, treeSelect },
    data() {
        return {
            treeSelectData: orgTreeList,
            treeDefaultProps: {
                children: 'children',
                label: 'label'
            },
            treeNodeKey: 'value',
            treeDefaultCheckedKeys: [],
            isAddState: '1',
            ksList: org,
            okrType: [
                { label: '部门', value: '10' },
                { label: '科室', value: '20' },
                { label: '政务外网调度', value: '30' },
                { label: '政务云调度', value: '60' },
                { label: '地市调度', value: '40' }
            ],
            fullscreenLoading: false,
            search: {
                subBelonging: localStorage.getItem('cityName'),
                taskType: '20'
            },
            dataList: [],
            typeOptions: [
                {
                    value: 0,
                    label: '待开始'
                },
                {
                    value: 1,
                    label: '进行中'
                },
                {
                    value: 2,
                    label: '已完成'
                },
                {
                    value: 3,
                    label: '已延期'
                },
                // {
                //     value: 4,
                //     label: '已终止'
                // }
            ],
            orgList: [],
            options: [],
            total: 6,
            pagination: {
                'pageNum': 1,
                'pageSize': 20
            },
            loading: false,
            searchContent: {},
            indexNum: []
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            if (to.path == '/workList/list' && !vm.getIsSearch()) {
                vm.onSubmit();
            }
        });
    },
    mounted() {
        this.onSubmit();
    },
    methods: {
        getTextToBr(text) {
            return text ? text.replace(/\n/g, '<br />') : '--'
        },
        popoverHide(checkedIds, checkedData) {
            this.search = { ...this.search, deptName: checkedIds }
        },
        changeTaskType() {
            this.search = { ...this.search, deptName: '' }
        },
        goDetail(row) {
            this.$router.push({
                path: row.taskType != '30' && row.taskType != '60' ? `/work/detail/${row.mainId}` : `/cloudwork/cloudDetail/${row.mainId}`
            })
        },
        down() {
            let params = { ...this.search }
            window.open(`${process.env.NODE_ENV === 'development' ? '/dev-api' : ''}/api/tasks/export?${qs.stringify(params)}`)
        },
        getIsSearch() {
            return Object.keys(this.searchContent).length === 0
        },
        getStateName(state) {
            let find = this.typeOptions.find(item => item.value == state)
            return find?.label || state || ''
        },
        truncateToFixed(value, decimals) {
            const integerPart = Math.trunc(value || 0); // 获取整数部分
            const decimalPart = value - integerPart; // 获取小数部分
            const factor = Math.pow(10, decimals);
            const truncatedDecimalPart = decimalPart < 0 ? Math.ceil(decimalPart * factor) / factor : Math.floor(decimalPart * factor) / factor; // 根据正负选择向上或向下截断
            return integerPart + truncatedDecimalPart; // 组合整数部分和小数部分
        },
        okrList() {
            let param = { ...this.search }
            if (!this.getIsSearch()) {
                this.fullscreenLoading = true
                getOkrList({ ...param }).then(res => {
                    let list = res.data.map(item => {
                        let secondList = []
                        item.subTasks.map((event) => {
                            if (event.batchSubTasks.length) {
                                event.batchSubTasks.map((val, idx) => {
                                    secondList.push({ ...val, ...event, idx })
                                })
                            } else {
                                secondList.push({ ...event, idx: 0 })
                            }
                        })
                        item.secondList = secondList || []
                        return item
                    })
                    let indexNum = []
                    list.map(item => {
                        indexNum.push([])
                    })
                    this.indexNum = [...indexNum]
                    this.dataList = list || []
                    this.fullscreenLoading = false
                }).catch((e) => {
                    this.fullscreenLoading = false
                })
            } else {
                this.$message({
                    type: 'warning',
                    message: '请输入搜索条件后查询!'
                })
            }
        },
        getColor(state) {
            let taskState = this.getStateName(state)
            const colors = {
                '超前': '#1ecd00',
                '正常': '#1ecd00',
                '已完成': '#1ecd00',
                '进行中': '#1890ff',
                '待开始': '#999',
                '已延期': '#ff4949',
                '落后': '#ff4949'
            }
            return colors[taskState]
        },
        reset() {
            this.search = {
                subBelonging: localStorage.getItem('cityName'),
                taskType: '20'
            }
            this.treeDefaultCheckedKeys = []
            this.orgList = []
            this.options = []
            this.onSubmit()
        },
        onSubmit() {
            this.searchContent = { ...this.search };
            this.okrList()
        },
        getPerson(acName) {
            this.loading = false;
            getPersonList({ acName }).then(res => {
                let personList = [];
                // if (this.search.subBelonging) {
                //     personList = res.filter(item => item.cityName == this.search.subBelonging) || []
                // } else {
                personList = res || []
                // }
                this.options = personList
            })
        },
        gerOrgList(cityName) {
            this.loading = false;
            getOrg({ cityName }).then(res => {
                this.orgList = res || []
            })
        },
        remoteMethod(query) {
            if (query !== '') {
                this.loading = true;
                this.getPerson(query.toLowerCase())
            } else {
                this.options = [];
            }
        },
        remoteMethodOrg(query) {
            if (query !== '') {
                this.loading = true;
                this.gerOrgList(query.toLowerCase())
            } else {
                this.orgList = [];
            }
        },
        getPagination(pagination) {
            this.pagination = pagination
            this.getList()
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }, dataList, idx) {
            if (columnIndex <= 3) {
                const _row = this.flitterData(dataList, 'subName', idx).one[rowIndex]
                const _col = _row > 0 ? 1 : 0
                return {
                    rowspan: _row,
                    colspan: _col,
                }
            }
        },
        flitterData(arr, name, idx) {
            let spanOneArr = []
            let concatOne = 0
            let checknum = 0;
            this.indexNum[idx] = []
            arr.forEach((item, index) => {
                if (index === 0) {
                    spanOneArr.push(1)
                    this.indexNum[idx].push(checknum)
                } else {
                    if (item[name] === arr[index - 1][name]) {
                        //第一列需合并相同内容的判断条件
                        spanOneArr[concatOne] += 1
                        spanOneArr.push(0)
                    } else {
                        checknum += 1;
                        spanOneArr.push(1)
                        concatOne = index
                    }
                    this.indexNum[idx].push(checknum)
                }
            })
            return {
                one: spanOneArr,
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.app-container {
    height: calc(100vh - 84px);
}

.table-box-y {
    height: calc(100% - 47px);
    overflow-y: auto;
}

/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
.table-box-y::-webkit-scrollbar {
    width: 8px;
    height: 0px;
    background-color: #F5F5F5;
}

/*定义滚动条轨道 内阴影+圆角*/
.table-box-y::-webkit-scrollbar-track {
    border-radius: 10px;
    background-color: #F5F5F5;
}

/*定义滑块 内阴影+圆角*/
.table-box-y::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #ccc;
}

.filter-container {
    ::v-deep .el-form-item {
        margin-bottom: 0;
    }
}

.table-box {
    ::v-deep .el-button--medium {
        padding: 0px 5px;
    }
}

.table-title {
    border: 1px solid #dfe6ec;
    border-bottom: 0;
    display: flex;
    padding: 10px 16px;
    justify-content: center;
    background: #edf2fa;
    font-size: 14px;

    .table-label {
        margin: 0 10px;
    }
}

.table-content {
    margin-bottom: 10px;
}

.empty-box {
    text-align: center;
    color: #999;
    line-height: 40px;
    margin-top: 100px;

    img {
        margin-left: -12px;
    }
}

b {
    color: #333;
}

.hover-go {
    cursor: pointer;
    text-decoration: underline;

    &:hover {
        color: rgb(24, 144, 255) !important;
    }
}
</style>